<!-- src/components/FileUpload.vue -->
<template>
  <div>
    <el-upload
      class="upload-demo"
      drag
      action=""
      :before-upload="handleBeforeUpload"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      wavelengths: [],
      intensities: []
    };
  },
  methods: {
    handleBeforeUpload(file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const content = event.target.result;
        this.extractData(content, file.name);
      };
      reader.readAsText(file);
      return false; // 阻止文件自动上传
    },
    extractData(content, fileName) {
      const lines = content.split('\n');
      const dataLines = lines.filter(line => this.isDataLine(line));

      this.wavelengths = [];
      this.intensities = [];

      dataLines.forEach(line => {
        const [wavelength, intensity] = line.split(',').map(Number);
        if (!isNaN(wavelength) && !isNaN(intensity)) {
          this.wavelengths.push(wavelength);
          this.intensities.push(intensity);
        }
      });

      // 将数据和文件名传递给父组件
      this.$emit('data-extracted', {
        wavelengths: this.wavelengths,
        intensities: this.intensities,
        fileName: fileName
      });
    },
    isDataLine(line) {
      // 正则表达式匹配数值数据行
      const regex = /^-?\d+(\.\d+)?,-?\d+(\.\d+)?$/;
      return regex.test(line.trim());
    }
  }
};
</script>

<style scoped>
.upload-demo {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  text-align: center;
  padding: 20px;
  cursor: pointer;
}
</style>
